//
//  JDCityUnionMessageViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/4/2.
//

import UIKit
import JXSegmentedView
import SwiftyJSON
import HXPhotoPicker

class JDCityUnionMessageViewController: JDBaseViewController {
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.isFirstLoad == false {
            self.getNetData(true,self.stateIndex)
        }
    }
    
    var dragonUserNumber: Int = 0
    
    var baseVC: UIViewController?
    
    var mainTableView: UITableView?
    
    var unionMessageModels: [JDRecruitModel?]?
    
//    var headerViewLabel: UILabel?
//    /// 发布记录
//    var releaseRecordButton: UIButton?
    var changeStateButton: UIButton?
    var changeTypeButton: UIButton?
    
    var stateIndex: Int = 1
    var isFirstLoad: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.setupUIElements()
        self.getNetData(true,self.stateIndex)
        NotificationCenter.default.addObserver(self, selector: #selector(notificationRefresh), name: Notification.Name("notificationRefresh"), object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(refreshDragonUserNum(_:)), name:  NSNotification.Name("refreshDragonUserNum"), object: nil)
        // Do any additional setup after loading the view.
    }
    
    @objc func notificationRefresh() {
        self.currentPage = 1
        self.getNetData(true,self.stateIndex)
    }
    
    @objc func refreshDragonUserNum(_ notify: Notification) {
        
        let info = notify.userInfo
        let count = (info?["dragonUserNum"] as? Int) ?? 0
        self.dragonUserNumber = count
//        self.headerViewLabel?.text = String.init(format: "尨圈人数 %zd", self.dragonUserNumber)
    }
    
    func setupUIElements() {
        
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view)
            make.bottom.equalTo(self.view)
        })
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.separatorStyle = .none
        self.mainTableView?.backgroundColor = self.commonColor
        
        self.mainTableView?.register(JDCityUnionMessageTableViewCell.self, forCellReuseIdentifier: "myCell")
        
        self.mainTableView?.tableHeaderView = self.customHeaderView()
        
        self.mainTableView?.addRefreshHeader { [weak self] in
            self?.currentPage = 1
            self?.getNetData(true,self?.stateIndex ?? 1)
        }
        
        self.mainTableView?.addRefreshFooter { [weak self] in
            self?.currentPage += 1
            self?.getNetData(false,self?.stateIndex ?? 1)
        }
        
    }
    
    func customHeaderView() -> UIView {
        let headerView = UIView()
        headerView.frame = CGRectMake(0, 0, screenWidth, 36+16)
        headerView.backgroundColor = self.commonColor
        
        self.changeTypeButton = UIButton.init(type: .custom)
        headerView.addSubview(self.changeTypeButton!)
        self.changeTypeButton?.snp.makeConstraints { make in
            make.top.bottom.equalTo(headerView)
            make.leading.equalTo(headerView).offset(24)
        }
//        self.changeTypeButton?.buttonConfig(normalTitle: "商讯分类", normalImageNamed: "", normalTitleColor: color("#333333"), titleFont: UIFont.systemFont(ofSize: 14, weight: .regular), backgroundColor: .clear)
        self.changeTypeButton?.addTarget(self, action: #selector(changeTypeAction), for: .touchUpInside)
        
        self.changeTypeButton?.setTitle("商讯分类", for: .normal)
        self.changeTypeButton?.setImage(UIImage(named: "arrow_down"), for: .normal)
      // 这里用appendImgV 重新处理一下
        self.changeTypeButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.changeTypeButton?.setTitleColor(color("#333333"), for: .normal)
        self.changeTypeButton?.semanticContentAttribute = .forceRightToLeft
        self.changeTypeButton?.isHidden = true

        
        self.changeStateButton = UIButton(type: .custom)
        headerView.addSubview(self.changeStateButton!)
        self.changeStateButton?.snp.makeConstraints { make in
            make.top.bottom.equalTo(headerView)
            make.trailing.equalTo(headerView).offset(-24)
        }
//        self.changeStateButton?.buttonConfig(normalTitle: "分类", normalImageNamed: "", normalTitleColor: color("#333333"), titleFont: UIFont.systemFont(ofSize: 14, weight: .regular), backgroundColor: .clear)
        self.changeStateButton?.addTarget(self, action: #selector(changeStateAction), for: .touchUpInside)
        
        self.changeStateButton?.setTitle("状态", for: .normal)
        self.changeStateButton?.setImage(UIImage(named: "arrow_down"), for: .normal)
      // 这里用appendImgV 重新处理一下
        self.changeStateButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.changeStateButton?.setTitleColor(color("#333333"), for: .normal)
        self.changeStateButton?.semanticContentAttribute = .forceRightToLeft
        
        
        
        
//        self.headerViewLabel = UILabel()
//        headerView.addSubview(self.headerViewLabel!)
//        self.headerViewLabel?.snp.makeConstraints({ make in
//            make.left.equalTo(headerView).offset(26)
//            make.height.equalTo(20)
//            //            make.top.equalTo(headerView)
//            make.centerY.equalTo(headerView)
//        })
//        self.headerViewLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 0)
//        self.headerViewLabel?.text = String.init(format: "尨圈人数 %zd", self.dragonUserNumber)
        
//        self.releaseRecordButton = UIButton(type: .custom)
//        headerView.addSubview(self.releaseRecordButton!)
//        self.releaseRecordButton?.snp.makeConstraints({ make in
//            make.right.equalTo(headerView).offset(-12)
//            make.centerY.equalTo(self.headerViewLabel!)
//            make.size.equalTo(CGSize(width: 76, height: 32))
//        })
//        self.releaseRecordButton?.backgroundColor = .white
//        self.releaseRecordButton?.layer.cornerRadius = 8
//        self.releaseRecordButton?.setTitle("发布记录", for: .normal)
//        self.releaseRecordButton?.setTitleColor(color("#333333"), for: .normal)
//        self.releaseRecordButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
//        self.releaseRecordButton?.addTarget(self, action: #selector(releaseRecordAction), for: .touchUpInside)
        return headerView
    }
    
    func getNetData(_ isRefresh: Bool = true,_ searchStatus: Int = 1) {
        
        var params = [String: Any]()
        params["pageNumber"] = self.currentPage
        params["pageSize"] = 10
        params["publishStatus"] = searchStatus
        
        JDNetWorkRequest(.getUnionNewsList(params)) { responseStr in
            self.isFirstLoad = false
            printLog("圈内商讯->列表数据:\(responseStr)")
//            {"msg":"ok","data":{"records":[],"pageNumber":1,"totalRow":0,"pageSize":10,"totalPage":0},"code":0}
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                // 成功
                if let recruitModels = [JDRecruitModel].deserialize(from: responseStr, designatedPath: "data.records") {
                    
                    if isRefresh {
                        self.unionMessageModels = recruitModels
                    } else {
                        self.unionMessageModels?.append(contentsOf: recruitModels)
                    }
                    
                    if recruitModels.count < 10 {
                        self.mainTableView?.reloadData()
                        self.mainTableView?.noMoreData()
                        return
                    }
                    
                }
            }
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
        } failure: { error in
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
            self.isFirstLoad = false
        } error: { errorCode in
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
            self.isFirstLoad = false
        }
    }
    
    @objc func changeStateAction() {
        print("状态")
        let pickerView = SimplePickerView()
        pickerView.modalPresentationStyle = .fullScreen
        pickerView.modalTransitionStyle = .coverVertical
        pickerView.SourceData = ["待审核","上架中","已结束","违规下架"]
        pickerView.confirmActionBlock = { [weak self] index in
            self?.stateIndex = index
            self?.getNetData(true, index)
            
        }
        self.showBottomCustomController(viewController: pickerView, screenHeightRation: 0.3)
    }
    
    @objc func changeTypeAction() {
        print("商讯分类")
        let pickerView = SimplePickerView()
        pickerView.modalPresentationStyle = .fullScreen
        pickerView.modalTransitionStyle = .coverVertical
        pickerView.SourceData = ["待审核","上架中","已结束","违规下架"]
        pickerView.confirmActionBlock = { [weak self] index in
//            发布状态(0：已发布未审核、1.已发布、2.到期终止、3.强制终止)
            self?.stateIndex = index
            self?.getNetData(true, index)
        }
        
        self.showBottomCustomController(viewController: pickerView, screenHeightRation: 0.3)
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
    @objc func releaseRecordAction() {
        printLog("龙商圈->发布记录")
        let releaseRecordVC = JDReleaseRecordViewController()
        self.baseVC?.hidesBottomBarPushViewController(releaseRecordVC)
    }
    
}

extension JDCityUnionMessageViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.unionMessageModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? JDCityUnionMessageTableViewCell
        
        let currentModel = self.unionMessageModels?[indexPath.row]
        
        cell?.refreshData(currentModel)
        
        cell?.sendPrivateMessageCallBack = {[weak self] remoteName, remoteId, recordId in
            let sendPrivateMessageVC = JDSendPrivateMessageViewController()
            sendPrivateMessageVC.remoteName = remoteName
            sendPrivateMessageVC.remoteId = remoteId
            sendPrivateMessageVC.recordId = recordId
            self?.baseVC?.hidesBottomBarPushViewController(sendPrivateMessageVC)
        }
        
        cell?.checkPrivateMessageCallBack = { [weak self] remoteName, remoteId, recordId in
            let privateMsgVC = JDPrivateMessageViewController()
            privateMsgVC.remoteName = remoteName
            privateMsgVC.remoteId = remoteId
            privateMsgVC.recordId = recordId
            self?.baseVC?.hidesBottomBarPushViewController(privateMsgVC)
        }
        
        cell?.imgVOne?.addTarget(self, action: #selector(openImageV(_:)), for: .touchUpInside)
        cell?.imgVTwo?.addTarget(self, action: #selector(openImageV(_:)), for: .touchUpInside)
        cell?.imgVThree?.addTarget(self, action: #selector(openImageV(_:)), for: .touchUpInside)
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    @objc func openImageV(_ button: UIButton) {
        if let image = button.imageView?.image {
            self.showImage(image)
        }
    }

    @objc func showImage(_ image: UIImage?) {
        
        let style: UIModalPresentationStyle = .custom
        var config = HXPhotoPicker.PhotoBrowser.Configuration()
        config.showDelete = false
        config.modalPresentationStyle = style
        
        /// 显示图片浏览器
        /// - Parameters:
        ///   - previewAssets: 对应 PhotoAsset 的数组
        ///   - pageIndex: 当前预览的位置
        ///   - config: 相关配置
        ///   - fromVC: 来源控制器
        ///   - transitionalImage: 初始转场动画时展示的 UIImage
        ///   - transitionHandler: 转场过渡
        ///   - deleteAssetHandler: 删除资源
        ///   - longPressHandler: 长按事件
        /// - Returns: 对应的 PhotoBrowser
        
        guard let currentImg = image else { return }
        HXPhotoPicker.PhotoBrowser.show([PhotoAsset.init(localImageAsset: LocalImageAsset.init(currentImg))], pageIndex: 0, config: config, fromVC: nil, transitionalImage: nil, transitionHandler: nil, transitionCompletion: nil, deleteAssetHandler: nil, longPressHandler: nil)
        
        
//        HXPhotoPicker.PhotoBrowser.show([PhotoAsset.init(networkImageAsset: NetworkImageAsset.init(thumbnailURL: URL(string: "https://ww1.sinaimg.cn/mw690/717076a7gy1hse09y4a0pj21jk2bcqms.jpg"), originalURL: URL(string: "https://ww1.sinaimg.cn/mw690/717076a7gy1hse09y4a0pj21jk2bcqms.jpg")))], pageIndex: 0, config: config, fromVC: nil, transitionalImage: nil, transitionHandler: nil, transitionCompletion: nil, deleteAssetHandler: nil, longPressHandler: nil)
    }
    
    
    
    
}

extension JDCityUnionMessageViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }

    func listDidAppear() {
        
    }

    func listDidDisappear() {
    }
}
